package com.hrm.attendance.service;

import com.hrm.attendance.dao.AttendanceConfigDao;
import com.hrm.attendance.dao.AttendanceDao;
import com.hrm.attendance.dao.UserDao;
import com.hrm.common.util.DateUtil;
import com.hrm.common.util.ExcelImportUtil;
import com.hrm.common.util.IdWorker;
import com.hrm.domain.attendance.entity.Attendance;
import com.hrm.domain.attendance.entity.AttendanceConfig;
import com.hrm.domain.attendance.vo.AtteUploadVo;
import com.hrm.domain.system.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class ExcelImportService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private AttendanceDao attendanceDao;
    @Autowired
    private AttendanceConfigDao attendanceConfigDao;
    @Autowired
    private IdWorker idWorker;

    @Value("${atte.holidays}")
    private String holidays;
    @Value("${atte.workingDays}")
    private String workingDays;


    public void importAttendanceExcel(MultipartFile file, String companyId) throws Exception {
        ExcelImportUtil<AtteUploadVo> util = new ExcelImportUtil<>(AtteUploadVo.class);
        List<AtteUploadVo> list = util.readExcel(file.getInputStream(), 1, 0);
        for (AtteUploadVo vo : list) {
            User user = userDao.findByMobile(vo.getMobile());
            //构造attendance实体类
            Attendance attendance = new Attendance(vo, user);
            //判断是否休假（周六周日、法定节假日）（数据库或文件中存放）
            if (holidays.contains(vo.getDay())) {
                attendance.setAdtStatu(23);//休息
            } else if (DateUtil.isWeekend(vo.getDay()) || !workingDays.contains(vo.getDay())) {
                attendance.setAdtStatu(23);
            } else {
                //判断迟到早退的状态(是否after上下班时间)
                AttendanceConfig config = attendanceConfigDao.findByCompanyIdAndDepartmentId(companyId, user.getDepartmentId());
                if (!DateUtil.comparingDate(config.getMorningStartTime(), vo.getInTime())) {
                    attendance.setAdtStatu(3);//迟到
                }else if (DateUtil.comparingDate(config.getAfternoonEndTime(), vo.getOutTime())) {
                    attendance.setAdtStatu(4);//早退
                }else {
                    attendance.setAdtStatu(1);//正常
                }
            }
            //查询用户是否已经有考勤记录，不存在则保存到数据库
            Attendance a = attendanceDao.findByUserIdAndDay(user.getId(), vo.getDay());
            if (a == null) {
                attendance.setId(new IdWorker().nextId() + "");
                attendanceDao.save(attendance);
            }
        }
    }
}
